﻿using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using IDEAMS.core;
using IDEAMS.model;
using IDEAMS.model.etalon;
using Microsoft.Win32;
using System;
using System.Linq;
using System.Windows;


namespace IDEAMS.view.setting
{
    /// <summary>
    /// AddEtalonDlg.xaml 的交互逻辑
    /// </summary>
    public partial class AddEtalonDlg : Window
    {
        public AddEtalonDlgViewModel windowViewModel;
        public AddEtalonDlg()
        {
            InitializeComponent();

            windowViewModel = new AddEtalonDlgViewModel();
            this.DataContext = windowViewModel;

            this.btnImport.Click += new RoutedEventHandler(Import_Click);
            this.btnOK.Click += new RoutedEventHandler(OK_Click);
            this.btnCancel.Click += new RoutedEventHandler(Cancel_Click);
        }

        private void OK_Click(object sender, RoutedEventArgs e)
        {
            if(windowViewModel.etalon.values.Count == 0)
            {
                MessageBox.Show("请加载数据","提示",MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            if (string.IsNullOrEmpty(tbName.Text))
            {
                MessageBox.Show("请输入标准具名称", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            Etalon etalon = TW_App.etalonCollection.Find(windowViewModel.etalon.name);
            if (etalon != null)
            {
                MessageBoxResult? result = MessageBox.Show("名称已经存在，是否更新", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if(result != MessageBoxResult.Yes)
                {
                    return;
                }
            }
            this.DialogResult = true;
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void Import_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Filter = "Excel Files (*.xls;*.xlsx)|*.xls;*.xlsx";
            openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            if (openFileDialog.ShowDialog() == true)
            {
                string filePath = openFileDialog.FileName;
                try
                {
                    windowViewModel.etalon.values.Clear();
                    // 使用using语句确保正确释放资源
                    using (SpreadsheetDocument doc = SpreadsheetDocument.Open(filePath, false))
                    {
                        WorkbookPart workbookPart = doc.WorkbookPart;
                        WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
                        SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();

                        // 从第二行开始读取
                        int rowIndex = 0;
                        foreach (Row row in sheetData.Elements<Row>())
                        {
                            // 仅读取第一列
                            if (rowIndex > 0) // 跳过第一行
                            {
                                Cell firstCell = row.Elements<Cell>().FirstOrDefault();
                                if (firstCell != null)
                                {
                                    string cellValue = GetCellValue(firstCell, workbookPart);
                                    windowViewModel.etalon.values.Add(double.Parse(cellValue));
                                }
                            }
                            rowIndex++;
                        }
                    }

                    windowViewModel.etalon.minValue = windowViewModel.etalon.values.Min();
                    windowViewModel.etalon.maxValue = windowViewModel.etalon.values.Max();
                    windowViewModel.etalon.count = windowViewModel.etalon.values.Count();
                }
                catch(Exception ex)
                {
                    MessageBox.Show("错误："+ex.Message,"错误",MessageBoxButton.OK,MessageBoxImage.Error);
                    return;
                }

            }
        }

        // 根据单元格类型获取单元格值
        private static string GetCellValue(Cell cell, WorkbookPart workbookPart)
        {
            string value = cell.InnerText;

            if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
            {
                return workbookPart.SharedStringTablePart.SharedStringTable
                    .Elements<SharedStringItem>().ElementAt(int.Parse(value)).InnerText;
            }
            else
            {
                return value;
            }
        }
    }

    public class AddEtalonDlgViewModel : ViewModelBase
    {
        public AddEtalonDlgViewModel()
        {
            etalon = new EtalonViewModel();
            etalon.values = new System.Collections.Generic.List<double>();
        }

        private EtalonViewModel m_etalon;
        public EtalonViewModel etalon
        {
            get { return m_etalon; }
            set
            {
                m_etalon = value;
                NotifyPropertyChanged();
            }
        }
    }
}
